package handlers

import (
	"book-master/cache"
	"book-master/models"
	"book-master/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.Query("username")
	password := c.Query("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "user_login_" + username
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if cacheData >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "错误三次，禁止登录",
		})
		return
	}
	var login models.User
	err := models.DB.Where("username = ?", username).First(&login).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户错误",
		})
		return
	}
	if login.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if pkg.Md5str(password) != login.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if cacheData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "错误三次，封禁2个小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "登录成功",
		"login": login,
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var list []models.Book
	redis_key := "book_list_" + strconv.Itoa(page)
	errData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if errData == "" {
		models.DB.Offset(offset).Limit(size).Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	}

	var count int64
	err := models.DB.Model(&models.Book{}).Count(&count).Error

	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": list,
	})
	return
}
func Detail(c *gin.Context) {
	var detail []models.Book
	models.DB.Find(&detail)
	c.JSON(200, gin.H{
		"code":   200,
		"msg":    "查询成功",
		"detail": detail,
	})
	return
}
